package com.xxl.job.executor.service.jobhandler;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.executor.dao.QxWeatherMapper;
import com.xxl.job.executor.model.QxWeather;
import com.xxl.job.executor.utils.CmUtil;
import com.xxl.job.executor.utils.ConstUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/*
"天气数据（一天）抓取";
 */
@Component
public class WeatherDataFor1dayTask {
    private static Logger logger = LoggerFactory.getLogger(WeatherDataFor1dayTask.class);

    private String taskContents;
    @Autowired
    private ConstUtil constUtil;
    @Autowired
    private QxWeatherMapper qxWeatherMapper;

    @XxlJob(value = "WeatherDataFor1dayTask",init = "init", destroy = "destroy")
    public ReturnT<String> WeatherDataFor1dayTask(String param) throws Exception {


//        if (constUtil == null) {
//            constUtil = SpringContextHolder.getBean(ConstUtil.class);
//        }
//        if (qxWeatherMapper == null) {
//            qxWeatherMapper = SpringContextHolder.getBean(QxWeatherMapper.class);
//        }
        String weatherUrl = "";
        HashMap<String,String> district = new HashMap<>();
        district.put(constUtil.distName,constUtil.distDodayId);
//        district.put("崂山","laoshan-district");
//        district.put("市南","shinan-district");
//        district.put("即墨","jimo");
//        district.put("胶州","jiaozhou");
//        district.put("黄岛","huangdao-district");
//        district.put("莱西","laixi");
//        district.put("平度","pingdu");
//        district.put("市北","shibei-district");
//        district.put("李沧","licang-district");
//        district.put("城阳","chengyang-district");
//          district.put("乌鲁木齐市","urumqi");
        // 青岛市天气数据网址前缀
        String weatherBaseUrl = constUtil.weatherBaseUrl2;
        // 循环获取各区市天气数据
        //        String szContent = openFile( "F:/ceshiHtml/mojiHTml.html");
        //        Parser parser = Parser.createParser(szContent, "utf-8");
        // 修改 无效Map Iterator
        Iterator<Map.Entry<String, String>> iterator  = district.entrySet().iterator();
        Map.Entry<String, String> entry = null;
        while (iterator.hasNext()) {
            entry = iterator.next();
            String key = entry.getKey();
            QxWeather qxWeather;
            try{
                weatherUrl = weatherBaseUrl+district.get(key);
                // 获取html文本内容
                Document doc = getHtml(weatherUrl, constUtil);
                if (doc == null) {
                    System.out.println("null");
                };
                // 获取当天时间
                String nowDate = CmUtil.date2day(null);
                // 获取地区
                String dist = key;
                // 获取一天天气数据
                Elements elements1 = doc.select("[class=info clearfix]");
                // 温度
                String temp = elements1.select("em").text();
                // 天气
                String skyCondition = elements1.select("b").text();
                // 更新时间
                String updateTime = doc.select("[class=detail_future_title]").select("span").text().substring(0,5);
                Elements elements2 = doc.select("[class=about clearfix]");
                // 相对湿度
                String humidity = elements2.select("span").text().substring(3,elements2.select("span").text().length());
                // 风向
                String windDirection = elements2.select("em").text()
                        .substring(0,elements2.select("em").text().indexOf("风")+1);
                // 风速
                String windSpeed = elements2.select("em").text()
                        .substring(elements2.select("em").text().indexOf("风")+2,elements2.select("em").text().length()-1);
                // 最高温
                Element elementsMax = doc.select("[class=day]").first();
                String maxTemp = elementsMax.select("b").text()
                        .substring(0,elementsMax.select("b").text().indexOf("°"));
                // 最低温
                Element elementsMin = doc.select("[class=day]").last();
                String minTemp = elementsMin.select("b").text()
                        .substring(0,elementsMin.select("b").text().indexOf("°"));

                ArrayList<String> weatherList = new ArrayList<>();
                weatherList.add(maxTemp);
                weatherList.add(minTemp);
                weatherList.add(windDirection);
                weatherList.add(windSpeed);
                weatherList.add(skyCondition);
                weatherList.add(temp);
                weatherList.add(humidity);
                // 查询天气数据（当天）是否存在
                String urbanDistrict = key;
                String wKind = "today";
                qxWeather = qxWeatherMapper.selectToday(nowDate,wKind,urbanDistrict);
                if(qxWeather==null){
                    // 不存在，插入一条新数据
                    try {
                        qxWeather = new QxWeather();
                        qxWeather.setId(CmUtil.getUUID());
                        qxWeather.setCreateTime(CmUtil.date2db(null));
                        qxWeather.setWtime(updateTime);
                        qxWeather.setDist(key);
                        qxWeather.setWdate(nowDate);
                        qxWeather.setTemp(temp);
                        qxWeather.setSkyCondition(skyCondition);
                        qxWeather.setHumidity(humidity);
                        qxWeather.setWindDirection(windDirection);
                        qxWeather.setWindSpeed(windSpeed);
                        qxWeather.setMaxTemp(maxTemp);
                        qxWeather.setMinTemp(minTemp);
                        // 数据类型(1day)
                        qxWeather.setWkind("today");
                        // 存入数据库
                        qxWeatherMapper.insertSelective(qxWeather);
                        this.taskContents = "插入"+dist+" "+nowDate+" "+"天气数据成功！";
                    }catch (Exception e){
                        e.printStackTrace();
                        this.taskContents = "插入"+dist+" "+nowDate+" "+"天气数据异常！";
                    }

                }else if(!qxWeather.toString2().equals(weatherList.toString())){
                    // 更新已有数据
                    try{
                        qxWeather.setWtime(updateTime);
                        qxWeather.setTemp(temp);
                        qxWeather.setSkyCondition(skyCondition);
                        qxWeather.setHumidity(humidity);
                        qxWeather.setWindDirection(windDirection);
                        qxWeather.setWindSpeed(windSpeed);
                        qxWeather.setMaxTemp(maxTemp);
                        qxWeather.setMinTemp(minTemp);
                        // 更新数据库
                        qxWeatherMapper.updateByPrimaryKeySelective(qxWeather);
                        this.taskContents = "更新"+dist+" "+nowDate+" "+"天气数据成功！";
                    }catch (Exception e){
                        e.printStackTrace();
                        this.taskContents = "更新"+dist+" "+nowDate+" "+"天气数据异常！";
                    }
                }
                this.taskContents = "日期转换成功！";
            }catch (Exception e){
                e.printStackTrace();
                this.taskContents = "日期转换异常！";
            }
        }
        return ReturnT.SUCCESS;
    }

    /**
     * 获取HTML内容
     *
     * @param url
     * @return
     */
    public static Document getHtml(String url, ConstUtil constUtil) {
        Document doc = null;
        try {
            if (constUtil.useProxy) {
                // 设置代理
                Proxy proxy = new Proxy(Proxy.Type.DIRECT.HTTP, new InetSocketAddress(constUtil.proxyId, constUtil.proxyPort));
                doc = Jsoup.connect(url)
                        .proxy(proxy)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            } else {
                doc = Jsoup.connect(url)
                        .userAgent("Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; MALC)")
                        .timeout(999999999)
                        .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                        .header("Accept-Encoding", "gzip, deflate")
                        .header("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3")
                        .header("Connection", "keep-alive")
                        //是忽略请求类型
                        .ignoreContentType(true)
                        .get();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return doc;
    }

    public static String openFile( String szFileName ) {
        String ENCODE = "utf-8";
        BufferedReader bis = null;
        try {
            bis = new BufferedReader(new InputStreamReader(new FileInputStream(new File(szFileName)), ENCODE));
            String szContent = "";
            String szTemp;

            while ((szTemp = bis.readLine()) != null) {
                szContent += szTemp + "\n";
            }
            return szContent;
        } catch (Exception e) {
            return "";
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void init(){
        logger.info("init");
    }
    public void destroy(){
        logger.info("destory");
    }
}
